# coding: utf-8

from datetime import timedelta, date

from flask_login import current_user
from wtforms import (
    StringField, TextAreaField, BooleanField, HiddenField, widgets, FileField
)

from flask_wtf.file import FileRequired, FileAllowed
from wtforms_components import (
    IntegerField, SelectMultipleField, DateField, DateTimeField, read_only,
)
from wtforms.validators import Optional, DataRequired

from app.auth.models import AdminUser
from ..constant import (
    Choice, Gender,
    get_tomorrow_fifteen_oclock
)
from ..forms import (
    WphForm, NonValidatingSelectField, NotChoices, MyDateTimeField,
    MultiCheckboxField
)
from app.ccws.constant import CallReason
from .constant import (
    UserType, UserStatus, UserLevel,
    FollowState, Aspiration, PaidFeel, Mastery,
    Scale, ContactFrequency, Injured, ImpressionDisplay,
    BusinessDisplay, AreaType, SmsMarketingLevel,
    GameRewardStatus, MarketingStatus
)
from common.constant import GiveVoucherReason
from .models import Area


class HiddenBoolean(IntegerField):
    widget = widgets.HiddenInput()

    def process_data(self, value):
        self.data = 1 if value else 0

    def process_formdata(self, valuelist):
        if valuelist:
            try:
                self.data = bool(int(valuelist[0]))
            except ValueError:
                self.data = None
                raise ValueError(self.gettext('Not a valid integer value'))


class HiddenInteger(IntegerField):
    widget = widgets.HiddenInput()


class BaseUserForm(WphForm):
    """
    新增用户与编辑用户表单基类
    """

    type = NonValidatingSelectField(
        '用户类型', coerce=int,
        choices=UserType.to_options(),
        validators=[Optional()]
    )
    level = NonValidatingSelectField(
        '用户等级', coerce=int,
        choices=[
            UserLevel.LEVEL_1.args,
            UserLevel.LEVEL_2.args,
            UserLevel.LEVEL_3.args,
        ],
        validators=[Optional()], default=UserLevel.LEVEL_1.value
    )
    mobile = StringField('手机号', validators=[DataRequired()])
    nickname = StringField('昵称', validators=[DataRequired()])
    gender = NonValidatingSelectField(
        '性别', coerce=int,
        choices=Gender.to_options(),
        default=Gender.MALE.value,
        validators=[Optional()]
    )
    prov = NonValidatingSelectField('省份', validators=[Optional()])
    city = NonValidatingSelectField(
        '城市', validators=[Optional()],
        choices=NotChoices, default=NotChoices[0][0],
    )
    addr = StringField('详细地址', validators=[Optional()])
    com = StringField('公司', validators=[Optional()])
    pos = StringField('职位', validators=[Optional()])
    active = NonValidatingSelectField(
        '是否激活', coerce=int,
        choices=Choice.to_options(),
        validators=[Optional()], default=Choice.YES.value
    )
    is_virt = NonValidatingSelectField(
        '是否虚拟', coerce=int,
        choices=Choice.to_options(),
        validators=[Optional()], default=Choice.NO.value
    )
    status = NonValidatingSelectField(
        '用户状态', coerce=int,
        choices=UserStatus.to_options(),
        validators=[Optional()], default=UserStatus.UNVERIFIED.value
    )
    remark = TextAreaField('备注', validators=[Optional()])
    sms_marketing_level = NonValidatingSelectField(
        '工程商分级',
        coerce=int,
        choices=NotChoices + SmsMarketingLevel.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0],
    )

    # 套餐信息
    has_pack = BooleanField('是否有套餐', default=False, validators=[Optional()])
    pack_prov = MultiCheckboxField('关注地区', validators=[Optional()], coerce=int)
    pack_bid_point = IntegerField('汇币', default=0, validators=[Optional()])

    publish_demand = BooleanField('发布项目', default=False, validators=[Optional()])
    com_summary = TextAreaField('公司简介', validators=[Optional()])

    # 下次回访信息
    next_outbound = BooleanField('设置回访', default=False, validators=[Optional()])
    next_outbound_schedule_time = DateTimeField(
        '回访时间',
        validators=[Optional()], default=get_tomorrow_fifteen_oclock,
    )
    next_outbound_call_reason = NonValidatingSelectField(
        '外呼原因', coerce=int,
        choices=CallReason.to_options(),
        validators=[Optional()], default=CallReason.VISIT_CALLBACK.value,
    )

    def __init__(self, *args, **kwargs):
        super(BaseUserForm, self).__init__(*args, **kwargs)
        provs = Area.query.filter_by(
            type=AreaType.PROV.value
        ).order_by(Area.id.asc())

        self.prov.choices = [
            (area.name, area.name)
            for area in provs
        ]

        cities = Area.query.filter_by(
            type=AreaType.CITY.value
        ).order_by(Area.id.asc())

        self.pack_prov.choices = [(i.id, i.name) for i in cities]
        read_only(self.pack_bid_point)


class CreateUserForm(BaseUserForm):
    """
    新建用户表单
    """
    pass


class DetailUserForm(BaseUserForm):
    """
    用户详情表单
    """
    mobile = StringField('手机号')
    wx_openid = StringField('微信openid', validators=[Optional()])
    credit = IntegerField('成就值', validators=[Optional()])
    phone_area_id = StringField('号码归属地', validators=[Optional()])
    war_zone_id = StringField('战区所属', validators=[Optional()])

    # 外呼记录信息
    outbound_record_id = HiddenField('外呼记录ID', validators=[Optional()])
    outbound_record_call_reason = StringField(
        '当前外呼原因', validators=[Optional()])
    outbound_record_remark = TextAreaField(
        '当前外呼结果', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(DetailUserForm, self).__init__(*args, **kwargs)
        read_only(self.outbound_record_call_reason)
        read_only(self.type)
        read_only(self.phone_area_id)
        read_only(self.war_zone_id)
        read_only(self.mobile)
        read_only(self.credit)
        if not current_user.is_administrator:
            read_only(self.level)


class UserTagForm(WphForm):
    """
    create by ld_wu 2017-08-30
    用户标签表单
    """
    user_id = HiddenInteger()
    follow_state = HiddenInteger(default=0)
    aspiration = HiddenInteger(default=0)
    gold_aspiration = HiddenInteger(default=0)
    supplier_aspiration = HiddenInteger(default=0)
    pay_aspiration = HiddenInteger(default=0)
    paid_feel = HiddenInteger(default=0)
    mastery = HiddenInteger(default=0)
    scale = HiddenInteger(default=0)
    contact_frequency = HiddenInteger(default=0)
    injured = HiddenInteger(default=0)
    # 对万屏会的评价
    few_order = HiddenBoolean(default=False)
    small_order = HiddenBoolean(default=False)
    fake_order = HiddenBoolean(default=False)
    crowd_order = HiddenBoolean(default=False)
    unfair_rule = HiddenBoolean(default=False)
    # 业务范围（安装、维修、租赁）
    install = HiddenBoolean(default=False)
    repair = HiddenBoolean(default=False)
    rent = HiddenBoolean(default=False)
    purchase = HiddenBoolean(default=False)


class SearchTagsForm(WphForm):
    """
    用户标签搜索表单
    """
    follow_state = NonValidatingSelectField(
        '关注公众号',
        coerce=int,
        choices=NotChoices + FollowState.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    aspiration = NonValidatingSelectField(
        '总体意愿',
        coerce=int,
        choices=NotChoices + Aspiration.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    gold_aspiration = NonValidatingSelectField(
        '金牌会员预期',
        coerce=int,
        choices=NotChoices + Aspiration.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    supplier_aspiration = NonValidatingSelectField(
        '批发商预期',
        coerce=int,
        choices=NotChoices + Aspiration.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    pay_aspiration = NonValidatingSelectField(
        '付费意愿',
        coerce=int,
        choices=NotChoices + Aspiration.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    paid_feel = NonValidatingSelectField(
        '付费感受',
        coerce=int,
        choices=NotChoices + PaidFeel.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    mastery = NonValidatingSelectField(
        '专业度',
        coerce=int,
        choices=NotChoices + Mastery.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    scale = NonValidatingSelectField(
        '实力规模',
        coerce=int,
        choices=NotChoices + Scale.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    contact_frequency = NonValidatingSelectField(
        '期望联系频率',
        coerce=int,
        choices=NotChoices + ContactFrequency.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    injured = NonValidatingSelectField(
        '被伤害程度',
        coerce=int,
        choices=NotChoices + Injured.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    impression = NonValidatingSelectField(
        '对万屏汇评价',
        choices=NotChoices + list(ImpressionDisplay.items()),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    business = NonValidatingSelectField(
        '业务范围',
        choices=NotChoices + list(BusinessDisplay.items()),
        validators=[Optional()],
        default=NotChoices[0][0]
    )


class SearchUserForm(WphForm):
    """
    搜索用户表单
    """

    id = IntegerField('用户ID', validators=[Optional()])
    wx_openid = StringField('微信openid', validators=[Optional()])
    type = NonValidatingSelectField(
        '用户类型', coerce=int,
        choices=NotChoices + UserType.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    level = NonValidatingSelectField(
        '用户等级', coerce=int,
        choices=NotChoices + UserLevel.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    mobile = StringField('手机号', validators=[Optional()])
    nickname = StringField('昵称', validators=[Optional()])
    com = StringField('公司名称', validators=[Optional()])
    gender = NonValidatingSelectField(
        '性别', coerce=int,
        choices=NotChoices + Gender.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    prov = NonValidatingSelectField(
        '省份', validators=[Optional()], default=NotChoices[0][0]
    )
    city = NonValidatingSelectField(
        '城市', validators=[Optional()],
        choices=NotChoices, default=NotChoices[0][0],
    )
    bind_wx_openid = NonValidatingSelectField(
        '绑定过微信', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    active = NonValidatingSelectField(
        '是否激活', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    is_virt = NonValidatingSelectField(
        '是否虚拟', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    status = NonValidatingSelectField(
        '用户状态', coerce=int,
        choices=NotChoices + UserStatus.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    binded_wx = BooleanField('已绑定微信', default=False, validators=[Optional()])
    black = BooleanField('是否拉黑', default=False, validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(SearchUserForm, self).__init__(*args, **kwargs)
        self.prov.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=1).order_by(Area.id.asc())
            ]
        self.city.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=2).order_by(Area.id.asc())
            ]


class SearchCancelAttentionUserForm(WphForm):
    """
    搜索取消用户表单
    """

    uid = IntegerField('用户ID', validators=[Optional()])
    mobile = StringField('手机号', validators=[Optional()])
    nickname = StringField('昵称', validators=[Optional()])
    cancel_attent_time_begin = DateTimeField('最早取关时间', validators=[Optional()],)
    cancel_attent_time_end = DateTimeField('最晚取关时间', validators=[Optional()],)
    current_attention = NonValidatingSelectField(
        '当前是否关注', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    has_recharge = NonValidatingSelectField(
        '充过值', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    has_partic = NonValidatingSelectField(
        '抢过单', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    has_pack = NonValidatingSelectField(
        '有套餐', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )


class SearchUserProtocolForm(WphForm):
    """
    搜索用户协议表单
    """

    user_id = IntegerField('用户ID', validators=[Optional()])
    mobile = StringField('手机号', validators=[Optional()])
    nickname = StringField('昵称', validators=[Optional()])


class ImportUserForm(WphForm):
    """
    工程商导入表单
    """
    files = FileField(
        '工程商文件',
        validators=[FileRequired(), FileAllowed(['xls', 'xlsx'])]
    )


class InviteBaseForm(WphForm):
    """
        create by ld_wu 2017-09-07
        客服拉新查询表单
        """

    call_time_begin = DateField('时间', validators=[Optional()])
    call_time_end = DateField(
        '至', validators=[Optional()], default=date.today()
    )
    aspiration = NonValidatingSelectField(
        '绑定意愿',
        validators=[Optional()],
        choices=NotChoices + Aspiration.to_options(),
        coerce=int,
        default=NotChoices[0][0]
    )

    mastery = NonValidatingSelectField(
        '专业度',
        validators=[Optional()],
        choices=NotChoices + Mastery.to_options(),
        coerce=int,
        default=NotChoices[0][0]
    )

    is_bind = NonValidatingSelectField(
        '是否加微信',
        validators=[Optional()],
        choices=NotChoices + Choice.to_options(),
        coerce=int,
        default=NotChoices[0][0]
    )

    demand_id = IntegerField('拉新订单', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(InviteBaseForm, self).__init__(*args, **kwargs)
        if not self.call_time_begin.raw_data:
            today = date.today()
            self.call_time_begin.data = date(today.year, today.month, 1)

    def condition_dict(self, delay=False):
        data = {
            key: value for key, value in self.data.items()
            if value != NotChoices[0][0] and value is not None and value != ''
        }
        if delay:
            data['call_time_end'] += timedelta(days=1)
        return data


class SearchInviteUserForm(WphForm):
    """
    create by ld_wu 2017-09-07
    客服拉新工程商查询表单
    """
    is_bind = BooleanField('绑定状态', default=False)
    send_date_begin = DateField('开始时间', default=date(2018, 7, 1))
    send_date_end = DateField('截止时间')
    status = NonValidatingSelectField(
        '正在营销',
        validators=[Optional()],
        coerce=int,
        choices=NotChoices + MarketingStatus.to_options(),
        default=NotChoices[0][0]
    )


class SearchBindForm(WphForm):
    """
    已加好友工程商查询表单
    """
    bind_user_id = NonValidatingSelectField(
        '添加人',
        validators=[Optional()],
        coerce=int,
        default=0
    )
    bind_date = DateField('加好友时间')

    def __init__(self, *args, **kwargs):
        super(SearchBindForm, self).__init__(*args, **kwargs)
        users = AdminUser.query.filter(
            AdminUser.deleted_at == 0
        )
        self.bind_user_id.choices = (
            [(0, '')] + [(user.id, user.nickname) for user in users]
        )


class SearchSmsMarketingUserForm(WphForm):
    """
    短信营销工程商查询表单
    """
    sms_marketing_level = NonValidatingSelectField(
        '工程商分级',
        coerce=int,
        choices=NotChoices + SmsMarketingLevel.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0],
    )
    respond_datetime_begin = DateTimeField(
        '最早回应时间', validators=[Optional()]
    )
    respond_datetime_end = DateTimeField(
        '最晚回应时间', validators=[Optional()]
    )


class SmsMarketingUserLevelForm(WphForm):
    """
    短信营销工程商分级表单
    """
    sms_marketing_level = NonValidatingSelectField(
        '工程商分级',
        coerce=int,
        choices=SmsMarketingLevel.to_options(),
        validators=[Optional()],
    )

    # 下次回访信息
    next_outbound = BooleanField('设置回访', default=False, validators=[Optional()])
    next_outbound_schedule_time = DateTimeField(
        '回访时间',
        validators=[Optional()],
        default=get_tomorrow_fifteen_oclock
    )
    next_outbound_call_reason = NonValidatingSelectField(
        '外呼原因', coerce=int,
        choices=CallReason.to_options(),
        validators=[Optional()],
        default=CallReason.INVITE_NEW_USER.value,
    )


class SearchPaidUserForm(WphForm):
    """
    created by chenhj at 2017/12/12

    """
    partic_at_begin = MyDateTimeField('最早抢单时间', validators=[Optional()])
    partic_at_end = MyDateTimeField('最晚抢单时间', validators=[Optional()])
    provs = SelectMultipleField('省份', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(SearchPaidUserForm, self).__init__(*args, **kwargs)
        self.provs.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(
                    type=AreaType.PROV.value
                ).order_by(Area.id.asc())
            ]


class SearchEngineerForm(WphForm):
    """
    拉新工程商列表
    """
    mobile = StringField('电话', validators=[Optional()])
    sms_marketing_level = NonValidatingSelectField(
        '分级',
        validators=[Optional()],
        choices=NotChoices+SmsMarketingLevel.to_options(),
        default=NotChoices[0][0],
        coerce=int
    )
    city = NonValidatingSelectField(
        '城市', validators=[Optional()],
        choices=NotChoices, default=NotChoices[0][0]
    )

    current_wx_openid = NonValidatingSelectField(
        '当前绑定状况',
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()],
        default=NotChoices[0][0]
    )

    def __init__(self, *args, **kwargs):
        super(SearchEngineerForm, self).__init__(*args, **kwargs)
        self.city.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=2).order_by(Area.id.asc())
            ]


class GameRewardForm(WphForm):
    status = NonValidatingSelectField(
        '兑换状态',
        validators=[Optional()],
        choices=NotChoices + GameRewardStatus.to_options(),
        coerce=int,
        default=NotChoices[0][0]
    )


class GiveVoucherForm(WphForm):
    grant_date = DateField('赠送时间', validators=[Optional()])
    user_id = StringField('受赠人ID', validators=[Optional()])
    nickname = StringField('受赠人昵称', validators=[Optional()])
    operator_id = NonValidatingSelectField(
        '赠送人',
        validators=[Optional()],
        coerce=int,
        default=NotChoices[0][0]
    )
    reason = NonValidatingSelectField(
        '赠送理由',
        validators=[Optional()],
        choices=NotChoices + GiveVoucherReason.to_options(),
        coerce=int,
        default=NotChoices[0][0]
    )

    def __init__(self, *args, **kwargs):
        super(GiveVoucherForm, self).__init__(*args, **kwargs)
        admin_users = AdminUser.query.filter(
            AdminUser.id != 0
        )
        self.operator_id.choices = NotChoices + [
            (admin_user.id, admin_user.nickname)
            for admin_user in admin_users
        ]


class VoucherGiftForm(WphForm):
    count = StringField('赠送券数', validators=[Optional()])
    give_day_val = StringField('有效天数', default=30, validators=[Optional()])
    reason = NonValidatingSelectField(
        '赠送理由:',
        validators=[Optional()],
        choices=NotChoices + [
            x for x in GiveVoucherReason.to_options()
            if x[0] not in (
                GiveVoucherReason.SYSTEM_GIFT.value,
                GiveVoucherReason.SYSTEM_INIT.value,
            )
        ],
        coerce=int,
        default=GiveVoucherReason.REFUND_OVERTIME_COMPENSATION.value
    )


class UserLevelForm(WphForm):
    user_id = IntegerField('用户ID', validators=[Optional()])
